import { Icon } from "@/ui/Icons/Icon";
import React, { useMemo } from "react";
import { PaginationI } from "@/models/common";
import cls from "@/styles/components/Pagination.module.scss";

type Props = {
  pagination: PaginationI;
};

export const Pagination = ({ pagination }: Props) => {
  const { pageIndex, pageCount, onChange } = pagination;
  const isFirst = pageIndex === 1;
  const isLast = pageIndex === pageCount;

  const nums = useMemo(() => {
    if (pageCount === 1) return [1];
    if (pageCount === 2) return [1, 2];
    if (pageCount === 3 || isFirst) return [1, 2, 3];

    if (isLast) return [pageIndex - 2, pageIndex - 1, pageIndex];

    return [pageIndex - 1, pageIndex, pageIndex + 1];
  }, [pageIndex, pageCount, isFirst, isLast]);

  return (
    <div className={cls.wrapper}>
      <div className={cls.root}>
        <button
          className={cls.prev}
          type="button"
          disabled={isFirst}
          onClick={() => {
            onChange(pageIndex - 1);
          }}
        >
          Назад
        </button>

        {nums.map((num) => {
          return (
            <button
              key={num}
              className={cls.num}
              type="button"
              data-pg-active={pageIndex === num}
              onClick={() => {
                onChange(num);
              }}
            >
              {num}
            </button>
          );
        })}

        <button
          className={cls.next}
          type="button"
          disabled={isLast}
          onClick={() => {
            onChange(pageIndex + 1);
          }}
        >
          Вперед
        </button>
      </div>
    </div>
  );
};
